<template>
	<div class="user-index">
		<a-modal
			v-model:visible="props.visible"
			class="user-modal"
			width="80%"
			@ok="handleOk"
			height="75%"
			:footer="null"
			@cancel="cancel"
		>
			<h3>{{ props.serial ? '取消挂失' : '挂失' }}</h3>
			<div class="content">
				<a-descriptions
					bordered
					:column="1"
					:labelStyle="{
						background: '#F3F3F3',
						border: '1px solid #CACACA',
					}"
					:contentStyle="{
						border: '1px solid #CACACA',
					}"
				>
					<a-descriptions-item label="加密锁序列号">
						<span v-if="props.serial">{{ fromData.serial }}</span>
						<a-input
							v-else
							v-model:value="fromData.serial"
							placeholder="请输入"
							@blur="getBaseInfo"
						/>
						<!-- <EditSelect
							v-else
							ref="serialValue"
							:selectData="sns"
							:value="fromData.serial"
							@changeValue="changeValue"
						/> -->
					</a-descriptions-item>
					<a-descriptions-item label="加密锁状态">
						<!-- <span
							class="status"
							v-if="
								selectDog &&
								!once &&
								(selectDog.status == 1 || selectDog.status == 3)
							"
							>生效中</span
						>
						<span
							class="status"
							v-if="selectDog && selectDog.status == 2 && !once"
							>不可用</span
						> -->
						<span>{{ statusMap[selectDog?.status] ?? '' }}</span>
					</a-descriptions-item>
					<!-- <a-descriptions-item label="购买时间">
						{{ recDate }}
					</a-descriptions-item> -->
					<a-descriptions-item label="是否补锁" v-if="!props.serial">
						<a-select
							v-model:value="fromData.extend1"
							style="width: 100%"
							placeholder="请选择"
							:bordered="false"
						>
							<a-select-option :value="1">是</a-select-option>
							<a-select-option :value="0">否</a-select-option>
						</a-select>
					</a-descriptions-item>
					<a-descriptions-item label="联系人">
						{{ maskName(fromData.callUserName) }}
					</a-descriptions-item>
					<a-descriptions-item label="联系电话">
						{{ maskPhoneNumber(fromData.tel) }}
					</a-descriptions-item>
					<a-descriptions-item label="短信验证码">
						<div class="message">
							<a-input
								v-model:value="fromData.code"
								placeholder="请输入验证码"
							/>
							<a-button @click="smsCode">{{
								codeNum != 60
									? '倒计时' + codeNum
									: '发送验证码'
							}}</a-button>
						</div>
					</a-descriptions-item>
					<!-- <a-descriptions-item label="设备名称">{{
						selectDog.machineId || machineId
					}}</a-descriptions-item>
					<a-descriptions-item label="已绑定设备">{{
						hostname
					}}</a-descriptions-item> -->
					
					<a-descriptions-item :label="props.serial ? '取消挂失说明' : '挂失说明'">
						<a-textarea
							v-model:value="fromData.description"
							:placeholder="`请输入${props.serial ? '取消挂失' : '挂失'}说明，1000个字以内`"
							:maxlength="1000"
							:rows="4"
						/>
					</a-descriptions-item>
				</a-descriptions>
			</div>
			<!-- <a-alert type="error" v-if="error" :message="errmsg" banner /> -->
			<div class="footer">
				<div class="left">
					<span v-if="!props.serial" class="desc"
						>挂失申请后，24小时内会有专人处理，请耐心等待。</span
					>
					<span class="info">客服热线：400-005-8008</span>
				</div>
				<div class="btn-list">
					<a-button @click="cancel">取消</a-button>
					<a-button
						type="primary"
						@click="handleOk"
						:loading="loading"
						>提交</a-button
					>
				</div>
			</div>
		</a-modal>
	</div>
</template>
<script setup>
import { ref, defineProps, reactive, watch, onMounted } from 'vue';
import { requestHttp } from '@/api/main.js';
import EditSelect from '@/components/EditSelect.vue';
const serialValue = ref();
const machineId = ref('');

import { message, notification } from 'ant-design-vue';
const props = defineProps(['visible', 'serial']);
const emits = defineEmits(['update:visible', 'updateSerial']);
let fromData = ref({
	serial: null,
	status: '0',
	applyType: 2,
	callUserName: '',
	tel: '',
	description: '',
	code: '',
	extend1: 1,
});
const statusMap = {
	0: '应用中',
	1: '已挂失',
	2: '已解绑',
	3: '已作废',
	9: '未使用'
}
let recDate = ref('');
onMounted(() => {});
let selectDog = ref({});
let hostname = ref();
let once = ref(true);
let loading = ref(false);

let sns = ref([]);
const maskName = (name) => {
    const trimmed = name.trim();
    const len = trimmed.length;
    if (len === 2) {
        // 两字姓名：替换第二个字
        return trimmed[0] + '*';
    } else if (len >= 3) {
        // 三字及以上：保留首尾，中间替换为*
        const masked = '*'.repeat(len - 2);
        return trimmed[0] + masked + trimmed[len - 1];
    }
    // 其他情况直接返回
    return trimmed;
}
// 隐藏中间四位
const maskPhoneNumber = (phoneNumber) => {
    return phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1​**​​**​$2');
}
let getSn = () => {
	requestHttp('controller.manager.getSn').then((res) => {
		sns.value = res.data;
		console.log(res.data);
		/*fromData.value.serial = sns.value[0];*/
		getBaseInfo();
		getDogInfo();
	});
};
const changeValue = (value) => {
	once.value = false;
	console.log('ceshi ', value);
	fromData.value.serial = value;
	getBaseInfo();
	getDogInfo();
};
const reset = () => {
	machineId.value = '';
	// if(!props.serial){
	// 	serialValue.value.reset();
	// }
	fromData.value.serial = null;
	fromData.value.callUserName = '';
	fromData.value.tel = '';
	fromData.value.description = '';
	fromData.value.code = '';
	hostname.value = '';
	selectDog.value = {};
	recDate.value = '';
	fromData.value.extend1 = 1;
};
const cancel = () => {
	reset();
	once.value = true;
	emits('update:visible', false);
	emits('updateSerial', ''); 
};
let selectBaseInfo = ref({});
let getBaseInfo = () => {
	requestHttp('controller.admin.getHardwareBySerial', {
		serial: fromData.value.serial+"",
	}).then((res) => {
		console.log('挂失', res);
		// if (res.status === 200) {
		if (res.data) {
			fromData.value.callUserName =
				res.data.callUserName;
			fromData.value.tel = res.data.tel;
			// hostname.value = res.data.result.machineName;
			// machineId.value = res.data.result.machineId;
			selectBaseInfo.value = res.data;
			let time =
				res.data.recDate &&
				getNowFormatDate(res.data.recDate);
			recDate.value = time;
			selectDog.value = res.data;
		} else {
			fromData.value.callUserName = '';
			fromData.value.tel = '';
			// hostname.value = '';
			selectBaseInfo.value = null;
			// machineId.value = '';
			recDate.value = '';
			selectDog.value = {};
			// message.error("输入设备不存在，请重新输入");
		}
	});
};
const getNowFormatDate = (time) => {
	//获取当前时间
	var date = new Date(time);
	var seperator1 = '-';
	var seperator2 = ':';
	var month =
		date.getMonth() + 1 < 10
			? '0' + (date.getMonth() + 1)
			: date.getMonth() + 1;
	var strDate = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
	var currentdate =
		date.getFullYear() + seperator1 + month + seperator1 + strDate + ' ';
	return currentdate;
};
const openNotificationWithIcon = (error) => {
	notification['error']({
		message: '错误信息',
		description: error,
	});
};
const handleOk = () => {
	if(!props.serial && selectDog.value.status == 1) {
		openNotificationWithIcon('已挂失,不能重复提交');
		return;
	}
	if (!fromData.value.serial) {
		return openNotificationWithIcon('设备编码必填');
	}
	if (!fromData.value.tel) {
		return openNotificationWithIcon('联系方式必填');
	}
	if (!fromData.value.description) {
		return openNotificationWithIcon('请输入挂失说明');
	}
	if (!fromData.value.code) {
		return openNotificationWithIcon('手机验证码必填');
	}
	if (!selectBaseInfo.value.serial) {
		return openNotificationWithIcon('该设备不存在,请联系管理员');
	}
	if (selectBaseInfo.value.status == 2) {
		return openNotificationWithIcon('该设备已经挂失,不能重复提交');
	}
	loading.value = true;
	console.log('提交', fromData.value)
	fromData.value.serial = fromData.value.serial+"";
	if (props.serial) {
		requestHttp('controller.admin.clientCancelReportLoss', fromData.value).then((res) => {
			console.log('取消挂失返回值', res);
			loading.value = false;
			if (res.data.status != 200) {
				openNotificationWithIcon(res.data.message);
			} else {
				message.success('取消挂失成功');
				setTimeout(() => {
					cancel();
				}, 1000);
			}
		});
	} else {
		requestHttp('controller.admin.clientReportLoss', fromData.value).then((res) => {
			console.log('挂失返回值', res);
			loading.value = false;

			if (res.data.status != 200) {
				openNotificationWithIcon(res.data.message);
			} else {
				message.success('提交成功，请等待平台处理');
				setTimeout(() => {
					cancel();
				}, 1000);
			}
		});
	}
};
let getDogInfo = () => {
	requestHttp('controller.manager.read', {
		serial: fromData.value.serial,
	}).then((res) => {
		// if (res.status === 200) {
		// 	selectDog.value = res.data;
		// } else {
		// 	// openNotificationWithIcon("设备不存在");
		// 	selectDog.value = {};
		// }
		console.log('selectDog.value', selectDog.value);
	});
};
let clean = () => {
	fromData.value = {
		serial: null,
		status: '0',
		applyType: 2,
		callUserName: '',
		tel: '',
		description: '',
		code: '',
		extend1: 1,
	};
};
watch(
	() => props.visible,
	() => {
		if (props.visible) {
			// getSn();
		} else {
			clean();
		}
	}
);
watch(
  () => props.serial,
  (val) => {
    if (val) {
      fromData.value.serial = val;
	  getBaseInfo();
      once.value = false;
    }
  },
  {immediate: true},
);

const codeNum = ref(60);
let clearId = null;
let smsCode = async () => {
	if (codeNum.value != 60) return;
	if (fromData.value.tel) {
		let res = await requestHttp('controller.admin.smsCode', {
			tel: fromData.value.tel,
		});
		clearId = setInterval(() => {
			codeNum.value--;
			if (codeNum.value == 0) {
				clearInterval(clearId);
				codeNum.value = 60;
			}
		}, 1000);
	}
};
</script>

<style lang="scss" scoped>
h3 {
	font-size: 21px;
	color: #287cfa;
	text-align: center;
}
.message {
	position: relative;
	.ant-input {
		text-align: center;
		border: none;
	}
	.ant-btn {
		border: 1px solid #6590fc;
		color: #287cfa;
		position: absolute;
		right: 10px;
	}
}
:deep(.ant-descriptions-row) {
	height: 44px;
	line-height: 44px;
}
:deep(.ant-descriptions-row .ant-descriptions-item-label) {
	text-align: right;
	padding: 0 24px;
	width: 30%;
}
:deep(.ant-descriptions-row .ant-descriptions-item-content) {
	text-align: center;
	padding: 0 0px;
}
.content {
	height: 300px;
	overflow-y: auto;
	.title {
		display: block;
		font-size: 16px;
		color: #333333;
	}
	.desc {
		display: block;
		font-size: 14px;
		color: #2a2a2a;
	}
}
.status {
	color: #15b426;
}
.footer {
	display: flex;
	justify-content: space-between;
	align-items: flex-end;
	margin-top: 30px;
	.left {
		span {
			display: block;
		}
		.desc {
			font-size: 12px;
			color: #de3f3f;
		}
		.info {
			font-size: 12px;
			margin: 5px 0 0 0px;
		}
	}
	.btn-list {
		button + button {
			margin-left: 10px;
		}
	}
}
.ant-input {
	width: 100%;
	text-align: center;
	border: none;
	&:focus {
		box-shadow: none !important;
	}
	.ant-input-focused {
		box-shadow: none !important;
	}
}
</style>
<style>
.modal :global(.adm-button:not(.adm-button-default)) {
	border: none;
}
</style>
